// 1. React核心库
import React, { useRef, useState, useEffect } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, Space, Tag, Popconfirm, Select, Modal, Form, DatePicker, Input, message } from 'antd';

// 3. 图标库
import { PlusOutlined, EditOutlined, DeleteOutlined, UserOutlined, ReloadOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';

// 6. 工具库
import dayjs from 'dayjs';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { UserRoleAssignment, RoleExtension, User } from '@/services/generated';

const { TextArea } = Input;

const UserRolesPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState(false);
  const [assignModalVisible, setAssignModalVisible] = useState(false);
  const [assignForm] = Form.useForm();
  const [roles, setRoles] = useState<RoleExtension[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [assignLoading, setAssignLoading] = useState(false);

  // 删除操作
  const handleDelete = async (record: UserRoleAssignment) => {
    try {
      setLoading(true);
      await autoLoginInDev();
      await apiClients.permissions.permissionsUserRolesDestroy({ id: record.id! });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    } finally {
      setLoading(false);
    }
  };

  // 批量删除
  const handleBatchDelete = async (selectedRowKeys: React.Key[]) => {
    try {
      setLoading(true);
      await autoLoginInDev();
      await Promise.all(
        selectedRowKeys.map(id => apiClients.permissions.permissionsUserRolesDestroy({ id: Number(id) }))
      );
      message.success(`成功删除${selectedRowKeys.length}条记录`);
      actionRef.current?.reload();
    } catch (error) {
      message.error('批量删除失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载角色和用户数据
  useEffect(() => {
    loadRoles();
    loadUsers();
  }, []);

  const loadRoles = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.permissions.permissionsRolesList({
        pageSize: 100,
        status: 'active',
      });
      setRoles(response.data?.items || []);
    } catch (error) {
      console.error('加载角色列表失败:', error);
    }
  };

  const loadUsers = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.users.usersList({
        pageSize: 100,
        isActive: true,
      });
      setUsers(response.data?.items || []);
    } catch (error) {
      console.error('加载用户列表失败:', error);
    }
  };

  const columns: ProColumns<UserRoleAssignment>[] = [
    { title: 'ID', dataIndex: 'id', width: 80, sorter: true },
    {
      title: '用户',
      dataIndex: 'user_username',
      ellipsis: true,
      copyable: true,
      render: (text, record) => (
        <Space direction="vertical" size={0}>
          <span>{text}</span>
          <span style={{ fontSize: '12px', color: '#666' }}>
            {record.user_email}
          </span>
        </Space>
      ),
    },
    {
      title: '角色',
      dataIndex: 'role_name',
      width: 150,
      render: (text) => <Tag color="blue">{text}</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (text: any, record: any) => {
        let color = 'red';
        let statusText = '未知';
 
        if (record.status === 'active') {
          // 检查是否过期
          if (record.expires_at && record.expires_at !== null && record.expires_at !== '') {
            try {
              const expiresDate = dayjs(String(record.expires_at));
              if (expiresDate.isValid() && expiresDate.isBefore(dayjs())) {
                color = 'orange';
                statusText = '已过期';
              } else {
                color = 'green';
                statusText = '激活';
              }
            } catch (error) {
              color = 'green';
              statusText = '激活';
            }
          } else {
            color = 'green';
            statusText = '激活';
          }
        } else if (text === 'inactive') {
          color = 'red';
          statusText = '禁用';
        } else if (text === 'expired') {
          color = 'orange';
          statusText = '过期';
        }

        return <Tag color={color}>{statusText}</Tag>;
      },
      valueType: 'select',
      valueEnum: {
        active: { text: '激活', status: 'Success' },
        inactive: { text: '禁用', status: 'Error' },
        expired: { text: '过期', status: 'Warning' },
      },
    },
    { title: '分配时间', dataIndex: 'assigned_at', valueType: 'dateTime', sorter: true, search: false },
    {
      title: '过期时间',
      dataIndex: 'expires_at',
      width: 180,
      search: false,
      render: (text: any) => {
        if (!text || text === null || text === undefined || text === '') {
          return <span style={{ color: '#52c41a' }}>永不过期</span>;
        }
        try {
          const date = dayjs(String(text));
          if (!date.isValid()) {
            return <span style={{ color: '#52c41a' }}>永不过期</span>;
          }
          return date.format('YYYY-MM-DD HH:mm:ss');
        } catch (error) {
          return <span style={{ color: '#52c41a' }}>永不过期</span>;
        }
      },
    },
    { title: '分配人', dataIndex: 'assigned_by_username', width: 120, search: false },
    { title: '分配原因', dataIndex: 'reason', ellipsis: true, search: false },
    {
      title: '操作',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button type="link" size="small" href={`/permissions/user-roles/detail/${record.id}`}>详情</Button>
          <Button type="link" size="small" href={`/permissions/user-roles/edit/${record.id}`}>编辑</Button>
          <Popconfirm title="确定删除？删除后用户将失去该角色的权限" onConfirm={() => handleDelete(record)}>
            <Button type="link" size="small" danger loading={loading}>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理分配角色
  const handleAssignRole = () => {
    setAssignModalVisible(true);
    assignForm.resetFields();
  };

  // 提交角色分配
  const handleAssignSubmit = async (values: any) => {
    setAssignLoading(true);
    try {
      await autoLoginInDev();
      await apiClients.permissions.permissionsUserRolesAssignRoleCreate({
        userRoleAssignmentRequest: {
          user: values.user_id,
          role: values.role_id,
          expires_at: values.expires_at ? values.expires_at.toISOString() : undefined,
          reason: values.reason,
        } as any,
      });

      message.success('分配角色成功');
      setAssignModalVisible(false);
      actionRef.current?.reload();
    } catch (error) {
      message.error('分配角色失败');
    } finally {
      setAssignLoading(false);
    }
  };

  return (
    <>
      <PageContainer>
        <ProTable<UserRoleAssignment>
             scroll={{x: 'max-content'}}
          headerTitle="用户角色分配管理"
          actionRef={actionRef}
          rowKey="id"
          search={{ labelWidth: 'auto' }}
          pagination={{ pageSize: 20, showSizeChanger: true, showQuickJumper: true }}
          rowSelection={{
            type: 'checkbox',
            onChange: (selectedRowKeys) => {
              console.log('选中的行:', selectedRowKeys);
            },
          }}
          tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
            <Space size={24}>
              <span>已选择 {selectedRowKeys.length} 项</span>
              <Button type="link" size="small" onClick={onCleanSelected}>取消选择</Button>
            </Space>
          )}
          tableAlertOptionRender={({ selectedRowKeys }) => (
            <Space size={16}>
              <Popconfirm title={`确定删除选中的${selectedRowKeys.length}条记录？`} onConfirm={() => handleBatchDelete(selectedRowKeys)}>
                <Button type="link" size="small" danger>批量删除</Button>
              </Popconfirm>
            </Space>
          )}
          toolBarRender={() => [
            <Button key="assign" type="primary" icon={<UserOutlined />} onClick={handleAssignRole}>分配角色</Button>,
            <Button key="refresh" icon={<ReloadOutlined />} onClick={() => actionRef.current?.reload()}>刷新</Button>,
          ]}
          request={async (params, sort) => {
            try {
              await autoLoginInDev();
              const response = await apiClients.permissions.permissionsUserRolesList({
                page: params.current || 1,
                pageSize: params.pageSize || 20,
                search: params.user_username || params.role_name,
                status: params.status,
                user: params.user,
                role: params.role,
                ordering: sort && Object.keys(sort).length > 0 ?
                  Object.entries(sort).map(([key, value]) => value === 'ascend' ? key : `-${key}`).join(',') :
                  '-assigned_at',
              });
              return {
                data: response?.data?.items || [],
                success: true,
                total: response?.data?.total || 0
              };
            } catch (error) {
              message.error('获取数据失败');
              return { data: [], success: false, total: 0 };
            }
          }}
          columns={columns}
        />
      </PageContainer>

      {/* 分配角色弹窗 */}
      <Modal
        title="分配角色给用户"
        open={assignModalVisible}
        onCancel={() => setAssignModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={assignForm}
          layout="vertical"
          onFinish={handleAssignSubmit}
        >
          <Form.Item
            label="选择用户"
            name="user_id"
            rules={[{ required: true, message: '请选择用户' }]}
          >
            <Select
              placeholder="请选择用户"
              showSearch
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
              options={users.map(user => ({
                label: `${user.username} (${user.email})`,
                value: user.id,
              }))}
            />
          </Form.Item>

          <Form.Item
            label="选择角色"
            name="role_id"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select
              placeholder="请选择角色"
              options={roles.map(role => ({
                label: role.group?.name,
                value: role.id,
              }))}
            />
          </Form.Item>

          <Form.Item
            label="过期时间"
            name="expires_at"
          >
            <DatePicker
              showTime
              placeholder="选择过期时间（不选择则永不过期）"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            label="分配原因"
            name="reason"
          >
            <TextArea
              rows={3}
              placeholder="请输入分配原因"
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                loading={assignLoading}
              >
                确定分配
              </Button>
              <Button onClick={() => setAssignModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default UserRolesPage;
